package http.mapping;

import http.method.support.MethodParameter;
import io.netty.handler.codec.http.FullHttpRequest;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class HandlerMethod {
    private final Object bean;
    private final Method method;
    private final MethodParameter[] parameters;

    private FullHttpRequest req;

    private RequestMethod[] methodTypes;


    private static LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();


    public HandlerMethod(Object bean, Method method) {
       this(bean,method,null);
    }

    public HandlerMethod(Object bean, Method method, RequestMethod[] methodTypes) {
        this.bean = bean;
        this.method = method;
        this.methodTypes = methodTypes;
        this.parameters=initMethodParameters();
    }

    private MethodParameter[] initMethodParameters() {
        int count = this.method.getParameterCount();
        MethodParameter[] result = new MethodParameter[count];
        String[] parameterNames = discoverer.getParameterNames(method);
        Annotation[][] parameterAnnotations = this.method.getParameterAnnotations();

        for (int i = 0; i < count; i++) {
            Class paramterType=this.method.getParameterTypes()[i];

            MethodParameter parameter = new MethodParameter();
            parameter.setParameterType(paramterType);
            parameter.setParameterName(parameterNames[i]);
            parameter.setParameterAnnotations(parameterAnnotations[i]);
            result[i] = parameter;
        }
        return result;
    }

    public Object getBean() {
        return bean;
    }

    public Method getMethod() {
        return method;
    }

    public MethodParameter[] getParameters() {
        return parameters;
    }

    public FullHttpRequest getReq() {
        return req;
    }

    public void setReq(FullHttpRequest req) {
        this.req = req;
    }

    public RequestMethod[] getMethodTypes() {
        return methodTypes;
    }

    public void setMethodTypes(RequestMethod[] methodTypes) {
        this.methodTypes = methodTypes;
    }
}
